package edu.drexel.cs.eVoter.VoterClient;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class NationalResultsPanel extends ClientAbstractPanel 
	implements NationalListener 
{
	private static final long serialVersionUID = -8637020118942509057L;
	private JButton updateButton;
	private JTable  nationalTable;
	private Vector<String> columns;
	
	private Vector<Vector<String>> rowData;
	
	public NationalResultsPanel(ServerInterface si) 
	{
		super(si);
		si.addNationalListener( this );
		columns = new Vector<String>();
		columns.add( "Candidates" );
		columns.add( "Votes" );
		rowData = new Vector<Vector<String>>();
		rowData.add( new Vector<String>(2) );
		rowData.add( new Vector<String>(2) );
		rowData.add( new Vector<String>(2) );
		rowData.get(0).add( "No Data" );
		rowData.get(0).add( "0" );
		rowData.get(1).add( "No Data" );
		rowData.get(1).add( "No Data" );
		rowData.get(2).add( "No Data" );
		rowData.get(2).add( "0" );

		
		updateButton = new JButton("Update");
		updateButton.addActionListener( new ActionListener() 
		{	
			@Override
			public void actionPerformed(ActionEvent e) 
			{
				processUpdate( e );
			}
		});
		nationalTable = new JTable( rowData, columns );
		
		JScrollPane jsp;
		jsp = new JScrollPane( nationalTable );
		
		add( updateButton );
		add( jsp );
	}
	
	private void processUpdate( ActionEvent event )
	{
		myServerInterface.nationalResults();
	}
	
	@Override
	public void nationalData(Map<String, Integer> nData) 
	{
		// update the rowData
		Set<Entry<String,Integer>> set = nData.entrySet();
		
		Iterator<Entry<String, Integer>> iter = set.iterator();
		
		rowData.clear();
		
		while ( iter.hasNext() )
		{
			Entry<String, Integer> ent = iter.next();
			
			String candidate = ent.getKey();
			Integer votes = ent.getValue();
			
			System.out.println("\n\ncandidate = <" + candidate + "> and votes = <" + votes + ">");
			Vector<String> temp = new Vector<String>(2);
			temp.add( candidate );
			temp.add( votes.toString() );
			
			rowData.add( temp );
		}
		
		nationalTable.setModel(new DefaultTableModel( rowData, columns ) );
		
		System.out.println("Update Completed in nationalData, size was " + set.size() + " and " + rowData.size() );
	}

}
